<template>
  <el-form ref="formRef" :model="_form" :rules="rules" label-width="80px" size="small">
    <el-form-item label="组名称" prop="name">
      <el-input v-model.trim="_form.name" />
    </el-form-item>
    <el-form-item label="项目" prop="pid">
      <el-select v-model="_form.pid" clearable>
        <el-option
          v-for="item in projectOptions"
          :key="item.pid"
          :label="item.name"
          :value="item.pid"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="启用" prop="status">
      <el-checkbox v-model="_form.status" :true-label="1" :false-label="0" />
    </el-form-item>
    <remark v-model:remark="_form.remark" />
    <el-form-item>
      <drawer-footer :save-loading="saveLoading" @cancel="cancel" @confirm="confirm" />
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { computed, defineEmits, defineExpose, defineProps, PropType, ref } from 'vue'

import { ElMessage } from 'element-plus'

import DrawerFooter from '&/components/Drawer/Footer.vue'
import Remark from '&/components/Form/remark.vue'

import GroupApi from '@/api/backend/group'

import { commonTitleReg } from '@/utils/regExp'

import IBaseObj from '#/index'

const props = defineProps({
  form: {
    type: Object,
    default: () => {},
  },
  projectOptions: {
    type: Array as PropType<IBaseObj[]>,
    default: () => [],
  },
  isAdd: {
    type: Boolean,
    default: true,
  },
})

const emits = defineEmits(['update:form', 'cancel', 'confirm'])

const _form = computed({
  get() {
    return props.form
  },
  set() {
    emits('update:form')
  },
})

const rules = {
  name: [
    { required: true, message: '请输入组名称', trigger: 'blur' },
    { ...commonTitleReg, trigger: 'blur' },
  ],
  // pid: [{ required: true, message: '请选择项目', trigger: 'change' }]
}

const saveLoading = ref(false)

const formRef = ref()

const cancel = () => {
  emits('cancel')
}
const confirm = () => {
  formRef.value.validate(async (valid: Boolean) => {
    if (valid) {
      saveLoading.value = true
      try {
        const res = await GroupApi.saveGroup({ ..._form.value })

        const { status: statusCode } = res
        if (statusCode === 200) {
          if (props.isAdd) {
            ElMessage({ message: '创建成功!', type: 'success', duration: 1500 })
          } else {
            ElMessage({ message: '修改成功!', type: 'success', duration: 1500 })
          }
          emits('confirm')
        }
      } catch (error) {
        console.log(error)
      } finally {
        saveLoading.value = false
      }
    } else {
      return false
    }
  })
}
const clear = () => {
  formRef.value.resetFields()
}

defineExpose({
  clear,
})
</script>
